package com.atguigu.gmall.common.config.thread;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.*;

/**
 * @author lfy
 * @Description
 * @create 2023-07-21 16:46
 */
@EnableConfigurationProperties(ThreadPoolProperties.class)
//1、@ConfigurationProperties 2、自动把这个配置类组件放到容器中
@Configuration
public class AppThreadPoolConfiguration {



    @Value("${spring.application.name}")
    String applicationName;
    @Bean
    public ThreadPoolExecutor executor(ThreadPoolProperties threadPoolProperties){
        return new ThreadPoolExecutor(
                threadPoolProperties.getCore(),
                threadPoolProperties.getMax(),
                threadPoolProperties.getKeepAliveTime(),
                TimeUnit.MINUTES,
                new LinkedBlockingQueue<>(threadPoolProperties.getQueueSize()),
                new ThreadFactory(){
                    int i = 1;
                    @Override
                    public Thread newThread(Runnable r) {
                        Thread thread = new Thread(r);
                        thread.setName("服务["+applicationName+"]；线程-"+ i++);
                        return thread;
                    }
                },
                new ThreadPoolExecutor.CallerRunsPolicy()
        );
    }
}
